package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存基本套餐,用mp方法
        save(setmealDto);
        //  保存套餐和菜品管理数据.  获取套餐菜品关联数据
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //遍历套餐关联数据  给每一个设置id
        for (SetmealDish setmealDish : setmealDishes) {
            //设置套餐id
           // setmealDish.setSetmealId(setmealDto.getId());
            setmealDish.setSetmealId(setmealDto.getId());
        }
        //这个里面涉及哪个表了  批量添加SetmealDish;
        setmealDishService.saveBatch(setmealDishes);

    }

    @Override
    public void removeByIdWithDish(List<Long> ids) {
        //1: 先判断ids到底能不能删
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        // 查询 状态为1  在售状态
        wrapper.eq(Setmeal::getStatus,1);
        //查询 个数,将前端的ids 全部进行查询
        wrapper.in(Setmeal::getId,ids);
        //计算查询到的结果  计数   一共有几个符合结果
        int count = count(wrapper);
        //判断  如果count >0  就证明有在售状态的 产品
        if (count>0){
            throw new CustomException("此为在售,不可删除");
        }
        removeByIds(ids);
        //删除完套餐表,还需要删除套餐菜品关联表
        LambdaQueryWrapper<SetmealDish> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(SetmealDish::getSetmealId,ids);
        //开始状态;
        setmealDishService.remove(wrapper1);

    }
}
